<template>
  <div class="annex-config-container">
    <div class="type-container">
      <VueDraggableNext
        id="drag-container"
        v-model="typeList"
        chosenClass="drag-chosen-class"
        :animation="500"
        :forceFallback="true"
        :capture="true"
        handle=".drag-handle"
        @start="handelTypeDragStart"
        @end="handelTypeDragEnd"
      >
        <template v-if="typeList.length">
          <div
            class="type-item"
            :class="{ 'item-active': typeItemId === item.profileCategoryId }"
            v-for="item in typeList"
            :key="item.profileCategoryId"
          >
            <div class="type-item-label" @click="handelActiveField(item)">
              <span v-ellipsis="{ rows: 1, text: item.profileCategoryName }" />
            </div>
            <div class="item-icon">
              <GiSvgIcon style="margin-right: 10px" name="rectification-del" size="16" @click="handelDelType(item)"></GiSvgIcon>
              <GiSvgIcon class="drag-handle" name="drag-icon" size="16"></GiSvgIcon>
            </div>
          </div>
        </template>
        <a-empty v-else />
      </VueDraggableNext>
      <div class="add-type-button">
        <a-button type="primary" @click="handleAddType">
          <template #icon>
            <icon-plus />
          </template>
          添加资料分类
        </a-button>
      </div>
    </div>
    <div class="field-container">
      <div class="app-container field-header">
        <CustomTitle title="配置附件字段" />
        <span class="field-header-tip">（请设置任务填写/反馈数据中，哪些字段可以作为公开的客户资料）</span>
      </div>
      <div class="app-container field-content">
        <a-button type="primary" style="width: 136px" v-if="fieldList.length" @click="handleAddField">
          <template #icon>
            <icon-plus />
          </template>
          添加任务字段
        </a-button>
        <VueDraggableNext
          id="drag-field-container"
          v-model="fieldList"
          chosenClass="drag-chosen-field-class"
          :animation="500"
          :forceFallback="true"
          :capture="true"
          handle=".drag-field-handle"
          @start="handelFieldDragStart"
          @end="handelFieldDragEnd"
        >
          <template v-if="fieldList.length">
            <div class="field-item" v-for="(item, index) in fieldList">
              <a-select
                placeholder="请选择字段名称"
                @change="changeField($event, item) as any"
                v-model="item.fieldForm.fieldId"
                :disabled="!!item.fieldForm.fieldId"
                :show-header-on-empty="true"
              >
                <template #header>
                  <div class="field-item-search">
                    <a-input
                      v-autoFocus
                      style="border: 0"
                      placeholder="请输入关键词"
                      v-model="item.keyword"
                      @input="handleSearchField(item)"
                    />
                    <GiSvgIcon
                      name="searchBox-icon"
                      size="24"
                      style="margin-right: 18px; cursor: pointer"
                      @click="handleSearchField(item)"
                    />
                  </div>
                </template>
                <a-option v-for="optItem in item.filedOptions" :value="optItem.fieldExtendId" :key="optItem.fieldExtendId">{{
                  optItem.displayFieldName
                }}</a-option>
              </a-select>
              <a-input disabled v-model="item.fieldForm.fieldType" />
              <!--              <a-checkbox-->
              <!--                class="field-item-checkbox"-->
              <!--                v-model="item.fieldForm.isUsedContract"-->
              <!--                @change="handelSetAnnexFieldUse($event, item)"-->
              <!--                >在合同中使用</a-checkbox-->
              <!--              >-->
              <div class="item-icon">
                <GiSvgIcon
                  style="margin-right: 10px"
                  name="rectification-del"
                  size="16"
                  @click="handelDelField(index, item)"
                ></GiSvgIcon>
                <GiSvgIcon class="drag-field-handle" name="drag-icon" size="16"></GiSvgIcon>
              </div>
            </div>
          </template>
          <div class="field-empty" v-else>
            <GiSvgIcon name="annex-icon" size="137"></GiSvgIcon>
            <span class="field-empty-label">还没有配置附件字段</span>
            <a-button type="primary" style="width: 136px" @click="handleAddField">
              <template #icon>
                <icon-plus />
              </template>
              添加任务字段
            </a-button>
          </div>
        </VueDraggableNext>
      </div>
    </div>

    <!--  TODO:后续优化，可以封装通用弹窗  -->
    <!--  新增分类 start  -->
    <a-modal
      :visible="isAddType"
      @ok="handleAddTypeOk"
      @cancel="handleAddTypeCancel"
      width="486px"
      unmount-on-close
      :mask-closable="false"
      :closable="false"
    >
      <CustomTitle title="新增分类" />
      <div class="add-type-modal">
        <a-form :model="typeForm" :rules="typeFormRules" ref="typeFormRef">
          <a-form-item field="category" label="分类名称">
            <a-input placeholder="请输入分类名称" v-model.trim="typeForm.category" />
          </a-form-item>
        </a-form>
      </div>
      <template #footer>
        <a-button style="width: 92px; background-color: #f2f3f5" @click="handleAddTypeCancel">取消</a-button>
        <a-button style="width: 92px" type="primary" @click="handleAddTypeOk">确定</a-button>
      </template>
    </a-modal>
    <!--  新增分类 end  -->
    <!--  TODO:后续优化，可以封装通用删除弹窗  -->
    <!--  删除分类  -->
    <a-modal :visible="isShowDelModal" width="400px" :mask-closable="false" unmountOnClose :closable="false">
      <div class="modal-message">
        <div class="del-name">{{ delData.profileCategoryName }}</div>
        <div class="del-tip">确定删除该分类吗？</div>
      </div>
      <template #footer>
        <a-button style="width: 92px; background-color: #f2f3f5" @click="handleDelCancel">取消</a-button>
        <a-button style="width: 92px" type="primary" @click="handleDelOk">确定</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, getCurrentInstance } from "vue";
import _, { cloneDeep } from "lodash";
import { VueDraggableNext } from "vue-draggable-next";
import CustomTitle from "@/components/CustomTitle/index.vue";
import {
  annexConfigList,
  annexFieldList,
  delAnnexConfig,
  addAnnexConfig,
  sortAnnexConfig,
  addAnnexField,
  searchAllField,
  sortAnnexField,
  delAnnexField,
  setAnnexFieldUse
} from "@/apis";
import type { annexTypeDataItem, addAnnexFieldParams } from "@/apis";
import { Message } from "@arco-design/web-vue";

const { proxy }: any = getCurrentInstance();

/**
 * 分类
 */
const typeItemId = ref("");
const typeList = ref<annexTypeDataItem[]>([]);
const getAnnexConfigList = async () => {
  const { data } = await annexConfigList();
  typeList.value = data ?? [];
  if (typeList.value.length) {
    typeItemId.value = typeList.value[0].profileCategoryId;
    getAnnexFieldList();
  }
};
const handelActiveField = (item: any) => {
  typeItemId.value = item.profileCategoryId;
  getAnnexFieldList();
};
// 分类拖动排序
const catchOldList = ref<annexTypeDataItem[]>([]);
const handelTypeDragStart = () => {
  catchOldList.value = cloneDeep(typeList.value);
};
const handelTypeDragEnd = async () => {
  try {
    const ids = typeList.value.map((item: any) => item.profileCategoryId);
    await sortAnnexConfig(ids);
    Message.success("操作成功！");
  } catch (err) {
    typeList.value = cloneDeep(catchOldList.value);
  }
};

/**
 * 新建分类
 */
const isAddType = ref(false);
const isAddNodeType = ref(false);
const typeForm = ref({
  category: ""
});
const typeFormRules = {
  category: [
    { required: true, message: "请输入分类名称", trigger: "blur" },
    { maxLength: 32, message: "请输入32个字符以内", trigger: "blur" }
  ]
};
const handleAddType = () => {
  isAddNodeType.value = false;
  isAddType.value = true;
};
const handleAddTypeOk = async () => {
  const valid = await proxy.$refs.typeFormRef?.validate();
  if (valid) return;
  await addAnnexConfig(typeForm.value);
  getAnnexConfigList();
  Message.success("新建分类成功！");
  handleAddTypeCancel();
};
const handleAddTypeCancel = () => {
  typeForm.value = {
    category: ""
  };
  isAddType.value = false;
};

/**
 * 删除分类
 */
const isShowDelModal = ref(false);
const delData = ref<annexTypeDataItem>({});
const handelDelType = (data: any) => {
  delData.value = cloneDeep(data);
  isShowDelModal.value = true;
};
const handleDelOk = async () => {
  await delAnnexConfig(delData.value.profileCategoryId);
  Message.success("删除成功!");
  getAnnexConfigList();
  handleDelCancel();
};
const handleDelCancel = () => {
  isShowDelModal.value = false;
  delData.value = {} as annexTypeDataItem;
};

/**
 * 字段
 */
const fieldList = ref<any[]>([]);
const isSearchLoading = ref(false);
const initFieldForm: addAnnexFieldParams = {
  crmProfileCategoryId: "",
  fieldId: "",
  fieldName: "",
  title: "",
  fieldType: "字段类型"
};
const handleAddField = () => {
  fieldList.value.push({
    fieldForm: { ...initFieldForm },
    filedOptions: [
      // {
      //   displayFieldName: "",
      //   fieldExtendId: "field-8103002844460",
      //   fieldName: "TextInput",
      //   title: "单行文本输入",
      //   fieldType: "String"
      // },
      // {
      //   displayFieldName: "",
      //   fieldExtendId: "field-2856983823734",
      //   fieldName: "ImageUpload",
      //   title: "图片",
      //   fieldType: "Array"
      // }
    ]
  });
};
// 附件字段列表
const getAnnexFieldList = async () => {
  const { data } = await annexFieldList(typeItemId.value);
  const list = data ?? [];
  fieldList.value = list.map((item: any) => {
    const optionObj = {
      displayFieldName: item.title,
      fieldExtendId: item.fieldId,
      fieldName: item.fieldName,
      title: item.title,
      fieldType: item.fieldType
    };
    return {
      fieldForm: item,
      filedOptions: [{ ...optionObj }]
    };
  });
};
// 搜索
const getSearchAllField = async (item: any) => {
  if (!item.keyword) return;
  try {
    isSearchLoading.value = true;
    const { data } = await searchAllField(item.keyword);
    const listData = data ?? [];
    const isHas = listData.some((item: any) => item.fieldExtendId === item.fieldForm?.fieldId);
    const defaultData = {
      displayFieldName: "",
      fieldExtendId: item.fieldForm.fieldId,
      fieldName: item.fieldForm.fieldName,
      title: item.fieldForm.title,
      fieldType: item.fieldForm.fieldType
    };
    item.filedOptions = isHas ? [...listData] : ([{ ...defaultData }, ...listData] as any);
    isSearchLoading.value = false;
  } catch (err) {
    console.log(err);
    isSearchLoading.value = false;
  }
};
const handleSearchField = _.debounce(getSearchAllField, 500);
// 选择需要添加的字段
const fieldTypes = new Map([
  ["TextInput", "单行文本"],
  ["TextareaInput", "多行文本"],
  ["NumberInput", "数字"],
  ["DateTime", "日期"],
  ["SelectInput", "单选框"],
  ["MultipleSelect", "多选框"],
  ["CascaderInput", "地址"],
  ["ImageUpload", "图片"],
  ["VideoUpload", "视频"],
  ["FileUpload", "附件"],
  ["UserPicker", "选择成员"]
]);
const getFieldType = (fieldName: string) => {
  return fieldTypes.has(fieldName) ? fieldTypes.get(fieldName) : "未知";
};
const changeField = async (e: any, item: any) => {
  try {
    const fieldObj = item.filedOptions.find((item: any) => item.fieldExtendId === e);
    if (!_.isEmpty(fieldObj)) {
      item.fieldForm = {
        crmProfileCategoryId: typeItemId.value,
        fieldId: e,
        fieldName: fieldObj.fieldName,
        title: fieldObj.displayFieldName,
        fieldType: getFieldType(fieldObj.fieldName)
      };
      await addAnnexField(item.fieldForm);
      getAnnexFieldList();
      Message.success("新建字段成功！");
    }
  } catch (err) {
    item.fieldForm = { ...initFieldForm };
  }
};
// 删除
const handelDelField = async (index: number, item: any) => {
  const { crmProfileCategoryId, fieldId } = item.fieldForm;
  if (!crmProfileCategoryId || !fieldId) return fieldList.value?.splice(index, 1);
  await delAnnexField(item.fieldForm.id);
  getAnnexFieldList();
  Message.success("删除字段成功！");
};
// 字段排序
const catchOldFieldList = ref([]);
const handelFieldDragStart = () => {
  catchOldFieldList.value = cloneDeep(fieldList.value) as any;
};
const handelFieldDragEnd = async () => {
  try {
    const ids = fieldList.value.map((item: any) => item.fieldForm.id);
    await sortAnnexField(ids);
    Message.success("操作成功！");
  } catch (err) {
    fieldList.value = cloneDeep(catchOldFieldList.value);
  }
};

/**
 * 设置附件是否在合同中使用
 */
const handelSetAnnexFieldUse = async (e: any, item: any) => {
  try {
    await setAnnexFieldUse(item.fieldForm.id, e);
    Message.success("操作成功！");
  } catch (err) {
    item.fieldForm.isUsedContract = !item.fieldForm.isUsedContract;
  }
};

getAnnexConfigList();
</script>

<style scoped lang="scss">
@import "./annexConfig.scss";

:deep(.arco-table-header) th {
  background-color: #f2f6fc !important;
}
:deep(.arco-table-body) tr:nth-child(2n) td {
  background-color: #f5f7fa !important;
}
</style>
